// pages/advanceSell/advanceSell.js
const bannerService = require('../../../../api/bannerService.js')
const advanceSellService = require('../../../../api/advanceSellService.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    goodsList: [],
    page: 1,
    pageSize: 10,
    loading: false,
    loadText: '正在加载中...',
    noStoreData: false,
  },
  // banner跳转
  bannerJumping: function (e) {
    const that = this
    let bannerId = e.currentTarget.dataset.id
    const bannerList = that.data.banners
    let advertisementInfo = null
    bannerList.forEach(item => {
      if (item.id === bannerId) {
        advertisementInfo = item
      }
    });
    console.log(advertisementInfo)
    that.toAdPage(advertisementInfo, 'banner')
  },

  // 前往广告页
  toAdPage: function (pageInfo, pageType) {
    const that = this
    if (pageInfo.linkType === 'APP') {
      // 应用
      // 判断跳转模块
      if (pageInfo.appReturnType === 'MIAOSHA') {
        wx.navigateTo({
          url: '../../activity/seckill/seckill'
        })
      } else if (pageInfo.appReturnType === "RECHARGE") {
        wx.navigateTo({
          url: '../../myCard/recharge/recharge'
        })
      } else if (pageInfo.appReturnType === "MEAL") {
        //  餐饮
      } else if (pageInfo.appReturnType === "RECEIVECOUPON") {
        // 领券中心
        wx.navigateTo({
          url: '../../coupon/couponCenter/couponCenter'
        })
      } else if (pageInfo.appReturnType === "ADVANCE_SELL_PRODUCT") {
        // 预售商品
        wx.navigateTo({
          url: '../../activity/advanceSell/advanceSell'
        })
      } else if (pageInfo.appReturnType === "TEAM_BUYING") {
        // 团购
        wx.navigateTo({
          url: '../../fightGroup/fightGroup/fightGroup'
        })
      } else if (pageInfo.appReturnType === "SCOREMALL") {
        // 积分商场
        wx.navigateTo({
          url: '../../score/scoreMall/scoreMall'
        })
      } else if (pageInfo.appReturnType === "INVITE_MEMBER") {
        // 邀请好友
        wx.navigateTo({
          url: '../../invite/invite'
        })
      } else if (pageInfo.appReturnType === "MEMBER_CARD") {
        // 会员卡
        wx.navigateTo({
          url: '../../myCard/memberCard/memberCard'
        })
      } else if (pageInfo.appReturnType === "MY_COUPON") {
        // 我的优惠券
        wx.navigateTo({
          url: '../../coupon/myCoupon/myCoupon'
        })
      } else if (pageInfo.appReturnType === "NEWMBR") {
        // 新用户专享
        wx.navigateTo({
          url: '../../activity/newmbrActivity/newmbrActivity'
        })
      }
    } else if (pageInfo.linkType === 'GRADPRODUCT') {
      // 秒杀商品
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=secondkill'
      })
    } else if (pageInfo.linkType === 'PRODUCT') {
      // 商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=normal'
      })
    } else if (pageInfo.linkType === 'TEAMPRODUCT') {
      // 拼团商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.teamActivityId + '&storeId=' + app.globalData.storeInfo.id + '&type=group'
      })
    } else if (pageInfo.linkType === 'COUPONACTIVITYDETAILS') {
      if (app.globalData.userInfo) {
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../coupon/couponDetails/couponDetails?couponActivityId=' + pageInfo.couponActivityId + '&type=assign&isExternal=false'
          })
        } else {
          wx.showToast({
            title: '您还不是会员，请绑定手机号成为会员~',
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            that.handlePopupPhone()
          }, 2000);
        }
      }
    } else if (pageInfo.linkType === 'URL') {
      // 链接
      let url = null
      if (pageType === 'activity') {
        url = pageInfo.linkUrl
      } else if (pageType === 'banner') {
        url = pageInfo.link
      }
      var index = '?'
      let webUrl = url
      if (url.indexOf(index) > -1) {
        webUrl = webUrl + '&storeId=' + this.data.storeId + '&type=normal'
      }
      let urlData = {
        url: encodeURIComponent(webUrl)
      }
      console.log(webUrl, urlData)
      let jsonUrl = JSON.stringify(urlData)
      wx.navigateTo({
        url: '../../advertising/advertising?webUrl=' + jsonUrl
      })
    } else {

    }
  },
  // 获取预售商品列表
  getAdvanceSellGoodsList: function (page, pageSize) {
    const that = this
    let postData = {
      page: page,
      pageSize: pageSize,
      searchCount: true,
      status: 'STARTED'
    }
    advanceSellService.query(postData).then(res => {
      console.log(res)
      let tempList = []
      if (res.records) {
        res.records.forEach(item => {
          let tempItem = {
            ...item,
            advanceBalance: item.advanceBalance ? item.advanceBalance : 999
          }
          if (item.enable === true) {
            tempList.push(tempItem)
          }
        });
        console.log(tempList)
        that.setData({
          goodsList: tempList
        })
      }
    })
  },

  // 前往商品详情
  toGoodsDetail: function (val) {
    console.log(val)
    if (val.currentTarget.dataset.goodsnum === 0) {
      wx.showToast({
        title: '您来晚了，已经被预定光了',
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + val.currentTarget.dataset.productid + '&advanceId=' + val.currentTarget.dataset.advanceid + '&type=advanceSell'
      })
    }
  },
  toHome: function () {
    wx.switchTab({
      url: '../../index/index/index'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAdvanceSellGoodsList(this.data.page, this.data.pageSize)
    if (app.globalData.storeInfo) {
      // 获取banner图片getStoreBannerList
      bannerService.getStoreBannerList('ADVANCE', app.globalData.storeInfo.id).then(res => {
        console.log(res)
        this.setData({
          banners: res
        })
      })
    } else {
      bannerService.getBannerList('ADVANCE').then(res => {
        console.log(res)
        this.setData({
          banners: res
        })
      })
    }
    if (this.options.mobile && this.options.mobile != '' && this.options.mobile != undefined) {
      const mobile = this.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      loading: false
    })
    this.getAdvanceSellGoodsList(this.data.page, this.data.pageSize)
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      loading: true
    })
    const that = this
    let index = that.data.page
    index++
    const oldGoodsList = that.data.goodsList
    let newGoodsList = []
    let postData = {
      page: index,
      pageSize: that.data.pageSize,
      searchCount: true,
      status: 'STARTED'
    }
    console.log(postData)
    advanceSellService.query(postData).then(res => {
      console.log(res)
      let tempList = []
      if (res.records) {
        if (res.records.length !== 0) {
          res.records.forEach(item => {
            let tempItem = {
              ...item
            }
            if (item.enable === true) {
              tempList.push(tempItem)
            }
          });
          newGoodsList = oldGoodsList.concat(tempList)
          that.setData({
            goodsList: newGoodsList,
            page: index,
            loading: false
          })
        } else {
          wx.hideToast()
          that.setData({
            loading: true,
            loadText: '已经加载到底了~'
          })
        }
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        path: '/pages/mallModule/activity/advanceSell/advanceSell?mobile=' + memberId
      }
    }
  },

  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})